import { ElLoading, ElMessage, ElMessageBox, ElNotification } from 'element-plus'

let loadingInstance = null

function showMessage(type, content) {
  ElMessage({
    type,
    message: content,
    plain: true,
  })
}

function showAlert(type, content) {
  ElMessageBox.alert(content, '系统提示', { type })
}

function showNotify(type, options) {
  if (typeof options === 'string') {
    options = { message: options }
  }
  ElNotification[type]({
    title: '系统提示',
    ...options,
  })
}

const MessageHelper = {
  /** 消息提示 */
  message: {
    /** @param {string} content */
    info: content => showMessage('info', content),
    /** @param {string} content */
    success: content => showMessage('success', content),
    /** @param {string} content */
    warning: content => showMessage('warning', content),
    /** @param {string} content */
    error: content => showMessage('error', content),
  },

  /** 弹出框提示（阻塞） */
  alert: {
    /** @param {string} content */
    info: content => showAlert('info', content),
    /** @param {string} content */
    success: content => showAlert('success', content),
    /** @param {string} content */
    warning: content => showAlert('warning', content),
    /** @param {string} content */
    error: content => showAlert('error', content),
  },

  /** 通知提示（非阻塞） */
  notify: {
    /** @param {string | object} options */
    info: options => showNotify('info', options),
    /** @param {string | object} options */
    success: options => showNotify('success', options),
    /** @param {string | object} options */
    warning: options => showNotify('warning', options),
    /** @param {string | object} options */
    error: options => showNotify('error', options),
  },

  /** 确认弹窗（返回 Promise） */
  confirm(content) {
    return ElMessageBox.confirm(content, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  },

  /** 输入弹窗（返回 Promise） */
  prompt(content) {
    return ElMessageBox.prompt(content, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  },

  /** 遮罩 loading 控制 */
  loading: {
    /** 显示 loading 遮罩 */
    open(content = '加载中...') {
      if (!loadingInstance) {
        loadingInstance = ElLoading.service({
          lock: true,
          text: content,
          background: 'rgba(0, 0, 0, 0.7)',
        })
      }
    },
    /** 关闭 loading 遮罩 */
    close() {
      if (loadingInstance) {
        loadingInstance.close()
        loadingInstance = null
      }
    },
  },
}

export default MessageHelper
